package one.one.thirtyTwo;

import java.util.Arrays;

import edu.princeton.cs.algs4.StdDraw;

public class Histogram {

	static int max(int[] a) {
		int m = a[0];
		int r = 0;
		for (int i = 1; i < a.length; i++) {
			if (a[i] > m) {
				m = a[i];
				r = i;
			}
		}
		return r;
	}

	static void histo(int n, double l, double r, double[] a) {
		int[] res = new int[n];
		double s = (r - l) / n;
		double[] comps = new double[n + 1];
		comps[0] = l;
		comps[n] = r;
		for (int i = 1; i < n; i++) {
			comps[i] = l + i * s;
		}
		for (int i = 0; i < a.length; i++) {
			for (int j = 0; j < n; j++) {
				if (comps[j] < a[i] && a[i] < comps[j + 1]) {
					res[j]++;
				}
			}
		}
		System.out.println(Arrays.toString(comps));
		System.out.println(Arrays.toString(res));
		pain(res);
	}

	static void pain(int[] res) {
		
		double l = res.length;
		double h = res[max(res)];
		
		double xs = 1.0 / l;
		double[] xp = new double[(int) l + 1];
		xp[0] = 0.0;
		StdDraw.text(0, 0.05, "0");
		xp[(int) l] = 1.0;
		for (int i = 1; i < xp.length - 1; i++) {
			xp[i] = xs * i;
			StdDraw.text(xp[i], 0.05, xp[i]+"");
		}

		double ys = 0.8 / h;
		double[] yp = new double[(int) h + 1];
		yp[0] = 0.0;
		yp[(int) h] = 0.8;
		for (int i = 1; i < yp.length - 1; i++) {
			yp[i] = ys * i;
		}

		double x, y, xh, yh;
		for (int i = 0; i < res.length; i++) {
			if (res[i] != 0) {
				x = xp[i] + xs / 2;
				y = yp[res[i]] / 2;
				xh = xs / 2;
				yh = y;
				StdDraw.rectangle(x, y, xh, yh);
			}
		}

	}

	public static void main(String[] args) {
		int n = 4;
		double l = 0.9;
		double r = 5.1;
		double[] a = { 1.2, 1.5, 2.5, 3.5, 4.5 };
		histo(n, l, r, a);

	}

	public static void mains(String[] args) {
		StdDraw.filledRectangle(0.1, 0.2, 0.1, 0.2);
		int l = 1;
		int r = 9;
		int n = 4;
		int s = (r - l) / n;
		for (int i = 0; i < 4; i++) {
			System.out.println(l + i * s);
		}

		for (int i = 0; i < n; i++) {
			System.out.println((int) (l + i * s) + "-" + (int) (l + (i + 1) * s));
		}

		System.out.println("---");
		int rd = 6;
		System.out.println();
	}

}
